window.onload = function () {
    cutAll(1);
}

/**
 * 分页显示订单数据
 * @param pageNo
 */
function cutAll(pageNo) {
    axios.get("/order/cutAll", {
        params: {
            pageNo: pageNo
        }
    }).then(resp => {
        var info = resp.data;
        var str = "";
        info.list.forEach(n => {
            str += `<tr><td>${n.userName}</td><td>${n.orderDate}</td><td>${n.address}</td><td><input type="button" value="删除" onclick="del(${n.id})"><input type="button" value="修改" onclick="findById(${n.id})"></td></tr>`
        });
        $("data").innerHTML = str;


        var cutSrt = "";
        for (var i = 1; i <= info.totalPage; i++) {
            cutSrt += `<a href="javascript:cutAll(${i})" style="margin-left:10px">${i}</a>`;
        }
        $("cutDiv").innerHTML = cutSrt;
    });
}

function $(id) {
    return document.getElementById(id);
}

function showAddDiv() {
    $("addDiv").style.visibility = "visible";
}

function addOrder() {
    /**
     * 用get方法请求服务器
     */
    // axios.get("/order/add", {
    //     params: {
    //         userName: $("userName").value,
    //         address: $("address").value
    //     }
    // }).then(resp => {
    //     var info = resp.data;
    //     if (info == "OK") {
    //         cutAll(1);
    //         $("userName").value = null;
    //         $("address").value = null;
    //         $("addDiv").style.visibility = "hidden";
    //     }
    // })
    /**
     * 用post方法请求服务器
     * @type {URLSearchParams}
     */
    let paramObj = new URLSearchParams();
    //添加表单数据
    paramObj.append("userName", $("userName").value);
    paramObj.append("address", $("address").value);

//    向服务器发送AJAX请求
    axios.post("order/add", paramObj).then(
        resp => {
            var info = resp.data;
            if (info == "OK") {
                cutAll(1);
                $("userName").value = null;
                $("address").value = null;
                $("addDiv").style.visibility = "hidden";
            }
        });
}


function del(id) {
    axios.get("order/del", {
        params: {
            id
        }
    }).then(resp => {
        var info = resp.data;
        if (info == "OK") {
            cutAll("1")
        }
    })
}

function findById(id) {
    axios.get("/order/findById", {
        params: {
            id
        }

    }).then(resp => {
        var info = resp.data;
        //    将对象数据显现在页面
        $("nameSpan").innerHTML = info.userName;
        $("updateAddress").value = info.address;

        $("id").value = info.id;

        $("updateDiv").style.visibility = "visible";
    })
}

function updateOrder() {
    axios.get("/order/update", {
        params: {
            id: $("id").value,
            address: $("updateAddress").value
        }
    }).then(resp => {
        var info = resp.data;
        if (info == "ok") {
            cutAll(1);
            $("updateDiv").style.visibility = "hidden";
        }
    });
}